package com.sky.controller.admin;

import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.BaseException;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 员工管理
 */
@RestController
@RequestMapping("/admin/employee")
@Slf4j
public class EmployeeController {


    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("登录")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
        log.info("员工登录：{}", employeeLoginDTO);

        Employee employee = employeeService.login(employeeLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, employee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();

        return Result.success(employeeLoginVO);
    }

    /**
     * 退出
     *
     * @return
     *
     */
    @ApiOperation("登出")
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success();
    }
    @ApiOperation("新增员工")
    @PostMapping
    @ResponseBody
    public Result<String> insertemployee(@RequestBody EmployeeDTO employeeDTO)
    {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employee.setStatus(1);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateUser( BaseContext.getCurrentId());
        employee.setUpdateUser( BaseContext.getCurrentId());
        employeeService.insertemployee(employee);
        log.info("新增用户{}",employee);
        return Result.success();
    }
    @GetMapping("/page")
    @ApiOperation("分页查询")
    @ResponseBody
    public Result queryemployee(
            @RequestParam(required = false)
            String name,
            @RequestParam
            int page,
            @RequestParam
            int pageSize
            )
    {
        EmployeePageQueryDTO queryDTO= new EmployeePageQueryDTO(name,page,pageSize);
        log.info("员工分页查询，参数为{}",queryDTO);
        PageResult pageResult= employeeService.queryemployee(queryDTO);
        return Result.success(pageResult);
    }
    @ApiOperation("禁用和启用用户")
    @PostMapping("/status/{status}")
    public Result startorban(@PathVariable("status") Integer status, @RequestParam Long id)
    {
        //查询用户状态
        Employee employee = employeeService.selectbtid(id);
        log.info("查询到的用户为{}",employee);
        if(employee!=null) {
            if (employee.getStatus() == 1) {
                employee.setStatus(0);
            } else
                employee.setStatus(1);
        }else{
            throw new BaseException("用户不存在");
        }
        int i = employeeService.updateEmployee(id, status);
        if(i==1)
        {
            return Result.success();
        }else
        {
            return Result.error("更新失败");
        }
    }
    @ApiOperation("查找员工")
    @GetMapping("/{id}")
    @ResponseBody
    public Result<Employee> selectbyid(@PathVariable("id") Long id)
    {
        Employee employee = employeeService.selectbtid(id);
        return Result.success(employee);
    }
    @ApiOperation("更新员工")
    @ResponseBody
    @PutMapping
    public Result updatebyid(@RequestBody EmployeeDTO employeeDTO)
    {
        log.info("employeeDTO的值为{}",employeeDTO);
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());
        employee.setStatus(1);
        int count= employeeService.updatebyid(employee);
        log.info("count为{}",count);
        if (count==1)
        {
            return Result.success();
        }else
            return Result.error("编辑失败");
    }

}
